﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

using System;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using GalaSoft.MvvmLight.Command;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Enums;
using Rio.Framework.Pages.Manager;
using Rio.Framework.Pages.Models;

namespace Rio.Framework.Pages
{
    public partial class Login : INotifyPropertyChanged
    {
        #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Fields

        private string _loginName;
        private LoginValidator _loginValidator;
        private string _password;

        #endregion

        #region Properties

        public string LoginName
        {
            get { return _loginName; }
            set
            {
                _loginName = value;
                OnPropertyChanged("LoginName");
            }
        }

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                OnPropertyChanged("Password");
            }
        }

        public RelayCommand<object> LoginUserCommand { get; set; }

        #endregion

        #region Constructors

        public Login()
        {
            InitializeComponent();

            ValideControl.Header = Resx.GetLabel(ResxCommon.ERROR);

            //Set Validator
            _loginValidator = new LoginValidator();
            DataContext = _loginValidator;

            LoadLogo();

            InitLabel();

            HtmlPage.Plugin.Focus();
            TextBoxLogin.Focus();

            LayoutLogin.KeyDown += LoginKeyDown;
            LoginUserCommand = new RelayCommand<object>(OnLoginUserCommand);
        }

        #endregion

        private void LoadLogo()
        {
            string fullUri = HtmlPage.Document.DocumentUri.OriginalString;
            string path = fullUri.Substring(0, fullUri.IndexOf(HtmlPage.Document.DocumentUri.LocalPath));

            VariableDomainContext variableDomainContext = new VariableDomainContext();
            variableDomainContext.GetAppDomainAppVirtualPath(delegate(InvokeOperation<string> str)
            {
                StringBuilder url = new StringBuilder(path);

                if (str.Value != "/")
                    url.Append(str.Value);

                url.Append(GlobalWebContext.RioAppSettings["Logo"]);

                Logo.Source = new BitmapImage(new Uri(url.ToString(), UriKind.Absolute));

                HtmlPage.Plugin.Focus();
                TextBoxLogin.Focus();
            },
            null);
        }

        public void LoginUser()
        {
            // Update the validation
            UpdateBindingExpression(TextBoxLogin, TextBox.TextProperty);
            UpdateBindingExpression(PassBoxPassword, PasswordBox.PasswordProperty);

            if (!ValideControl.HasErrors)
            {
                IsEnabled = false;

                SplashScreenManager.Wait(this);

                LoginManager.Instance.AuthenticatedUserFailed += LoginManagerAuthenticatedUserFailed;
                LoginManager.Instance.AuthenticatedUser += LoginManagerAuthenticatedUser;
                LoginManager.Instance.LogUser(LoginName, Password);
            }
        }

        private void LoginManagerAuthenticatedUser(object sender, EventArgs e)
        {
            LoginManager.Instance.AuthenticatedUser -= LoginManagerAuthenticatedUser;
            LoginManager.Instance.AuthenticatedUserFailed -= LoginManagerAuthenticatedUserFailed;

            SplashScreenManager.Stop(this);

            if (!String.IsNullOrWhiteSpace(NavigationHelper.Instance.RedirectUrl))
            {
                NavigationHelper.Instance.NavigateToUri(NavigationHelper.Instance.RedirectUrl);
                NavigationHelper.Instance.ClearRedirectUrl();
            }
            else
                NavigationHelper.Instance.NavigateToApplication(ApplicationName.RioOffice);
        }

        private void LoginManagerAuthenticatedUserFailed(object sender, EventArgs e)
        {
            LoginManager.Instance.AuthenticatedUser -= LoginManagerAuthenticatedUser;
            LoginManager.Instance.AuthenticatedUserFailed -= LoginManagerAuthenticatedUserFailed;

            SplashScreenManager.Stop(this);

            MessageBoxChildWindow errorMessage = new MessageBoxChildWindow("",
                                                                           Resx.GetLabel(

                                                                               ResxLogin.ERROR_LOGIN),
                                                                           MessageBoxButtons.Ok,
                                                                           MessageBoxIcon.Warning);
            errorMessage.ShowDialog();

            IsEnabled = true;

            HtmlPage.Plugin.Focus();

            TextBoxLogin.SelectAll();
            TextBoxLogin.Focus();
        }

        private void InitLabel()
        {
            labLogin.Content = Resx.GetLabel(ResxLogin.LOGIN);
            labPassword.Content = Resx.GetLabel(ResxLogin.PASSWORD);
            buttonConnection.Content = Resx.GetLabel(ResxLogin.CONNECTION);
        }

        private void UpdateBindingExpression(DependencyObject obj, DependencyProperty prop)
        {
            BindingExpression bindingExpression = obj.ReadLocalValue(prop) as BindingExpression;

            if (bindingExpression != null)
            {
                bindingExpression.UpdateSource();
            }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void OnLoginUserCommand(object parameter)
        {
            LoginUser();
        }

        private void LoginKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                LoginUser();
        }
    }
}